<template>
    <div>
      <!-- 通知图标 -->
      <div class="notification-icon" @click="showNotifications = !showNotifications">
        <el-badge :value="notificationCount" :max="99" class="item">
          <i class="el-icon-bell"></i>
        </el-badge>
      </div>

      <!-- 通知面板 -->
      <el-drawer
        title="消息通知"
        :visible.sync="showNotifications"
        direction="rtl"
        size="30%"
      >
        <div class="notification-panel">
          <div class="notification-header">
            <span>未读消息 ({{ notificationCount }})</span>
            <el-button type="text" @click="clearNotifications">清空所有</el-button>
          </div>
          <div class="notification-list">
            <div
              v-for="notification in notifications"
              :key="notification.id"
              class="notification-item"
              :class="{ 'unread': !notification.read }"
              @click="markNotificationAsRead(notification)"
            >
              <div class="notification-content">
                <div class="notification-title">{{ notification.title }}</div>
                <div class="notification-message">{{ notification.content }}</div>
                <div class="notification-time">{{ notification.time }}</div>
              </div>
            </div>
          </div>
        </div>
      </el-drawer>

      <h1>商家订单管理</h1>
      <!-- 查询条件 -->
      <el-form :inline="true" :model="query" class="demo-form-inline">
      <el-form-item label="入库时间区间：">
        <el-date-picker
          v-model="query.dateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 350px;"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="订单状态：">
        <el-select v-model="query.orderState" placeholder="请选择订单状态" style="width: 200px;">
          <el-option label="全部" :value="null"></el-option>
          <el-option label="已创建" :value="1"></el-option>
          <el-option label="已确认" :value="2"></el-option>
          <el-option label="已接取" :value="3"></el-option>
          <el-option label="待接取" :value="4"></el-option>
          <el-option label="已入库" :value="5"></el-option>
          <el-option label="已取消" :value="6"></el-option>
          <el-option label="待分配" :value="7"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="站点：">
        <el-select
          v-model="query.siteId"
          filterable
          remote
          placeholder="请输入站点名称"
          :remote-method="fetchSites"
          :loading="loading"
          style="width: 200px;"
        >
          <el-option
            v-for="site in siteOptions"
            :key="site.value"
            :label="site.label"
            :value="site.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用户电话：">
        <el-input v-model="query.userPhone" placeholder="请输入用户电话" style="width: 200px;"></el-input>
      </el-form-item>
      <el-form-item label="临时工名字：">
        <el-input v-model="query.workName" placeholder="请输入临时工名字" style="width: 200px;"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchOrders">查询</el-button>
      </el-form-item>
    </el-form>
  
      <!-- 订单列表 -->
      <el-table :data="orders" style="width: 100%; margin-bottom: 20px;">
        <el-table-column prop="orderNumber" label="订单编号" width="180"></el-table-column>
        <el-table-column prop="userName" label="用户姓名" width="120"></el-table-column>
        <el-table-column prop="userPhone" label="用户电话" width="150"></el-table-column>
        <el-table-column prop="startTime" label="预约时间" width="180"></el-table-column>
        <el-table-column label="订单状态" width="120">
          <template #default="scope">
            {{ getOrderState(scope.row.orderState) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="成交金额" width="120"></el-table-column>
        <el-table-column prop="creatTime" label="创建时间" width="180"></el-table-column>
        <el-table-column prop="workName" label="临时工姓名" width="120"></el-table-column>
        <el-table-column label="站点" width="120">
          <template #default="scope">
            {{ getSiteName(scope.row.siteId) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button 
              v-if="scope.row.orderState === 1" 
              type="primary" 
              size="small" 
              @click="handleAssignSite(scope.row)"
            >分配站点</el-button>
            <!-- <el-button 
              v-if="scope.row.orderState !== 5 && scope.row.orderState !== 6 && scope.row.orderState !== 2" 
              type="danger" 
              size="small" 
              @click="handleCancelOrder(scope.row)"
            >取消订单</el-button> -->
            <el-button 
              type="info" 
              size="small" 
              @click="handleViewDetails(scope.row)"
            >查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页 -->
      <el-pagination
        background
        layout="total, prev, pager, next, sizes"
        :total="total"
        :page-size="query.pageSize"
        :page-sizes="[10, 20, 50]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="text-align: right;"
      ></el-pagination>
      
      <!-- 分配站点对话框 -->
      <el-dialog
        title="分配站点"
        :visible.sync="assignSiteDialogVisible"
        width="30%"
        :close-on-click-modal="false"
      >
        <el-form :model="{ siteId: selectedSiteId }" label-width="80px">
          <el-form-item label="站点">
            <el-select v-model="selectedSiteId" placeholder="请选择站点" style="width: 100%">
              <el-option
                v-for="site in siteOptions"
                :key="site.value"
                :label="site.label"
                :value="site.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="assignSiteDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmAssignSite">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 订单详情对话框 -->
      <el-dialog
        title="订单详情"
        :visible.sync="detailsDialogVisible"
        width="50%"
        :close-on-click-modal="false"
      >
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单编号">{{ currentOrderDetails.orderNumber }}</el-descriptions-item>
          <el-descriptions-item label="用户姓名">{{ currentOrderDetails.userName }}</el-descriptions-item>
          <el-descriptions-item label="用户电话">{{ currentOrderDetails.userPhone }}</el-descriptions-item>
          <el-descriptions-item label="预约时间">{{ currentOrderDetails.startTime }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">{{ getOrderState(currentOrderDetails.orderState) }}</el-descriptions-item>
          <el-descriptions-item label="成交金额">{{ currentOrderDetails.totalAmount }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentOrderDetails.creatTime }}</el-descriptions-item>
          <el-descriptions-item label="临时工姓名">{{ currentOrderDetails.workName }}</el-descriptions-item>
          <el-descriptions-item label="站点名称">{{ currentOrderDetails.siteName }}</el-descriptions-item>
          <el-descriptions-item label="用户地址" :span="2">{{ currentOrderDetails.userAddress }}</el-descriptions-item>
        </el-descriptions>

        <div class="waste-details" >
          <h3 style="margin: 20px 0;">废品详情</h3>
          <el-table 
            v-if="currentOrderDetails.wasteList && currentOrderDetails.wasteList.length > 0"
            :data="currentOrderDetails.wasteList" 
            style="width: 100%"
            border
          >
            <el-table-column prop="wasteInfo" label="废品简介" min-width="120">
              <template slot-scope="scope">
                {{ scope.row.wasteInfo || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="数量" width="100">
              <template slot-scope="scope">
                {{ scope.row.weight || '-' }} {{ scope.row.unit || '' }}
              </template>
            </el-table-column>
            <el-table-column label="单价" width="100">
              <template slot-scope="scope">
                ¥{{ scope.row.sastePrice || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="总价" width="100">
              <template slot-scope="scope">
                ¥{{ scope.row.sasteAllPrice || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="废品类型" width="120">
              <template slot-scope="scope">
                {{ getWasteTypeName(scope.row.sasteTypeId) || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="图片" width="120">
              <template slot-scope="scope">
                <el-image 
                  v-if="scope.row.wasteImage"
                  style="width: 60px; height: 60px; object-fit: cover;"
                  :src="scope.row.wasteImage"
                  :preview-src-list="[scope.row.wasteImage]">
                </el-image>
                <span v-else>无图片</span>
              </template>
            </el-table-column>
          </el-table>
          <div v-else class="no-data" style="text-align: center; padding: 20px; color: #909399;">
            暂无废品信息
          </div>
        </div>
      </el-dialog>
    </div>
  </template>
  <script>
  import axios from 'axios';
  import { webSocketClient } from '../utils/websocket';
  
  export default {
    data() {
      return {
        query: {
          dateRange: [],
          siteId: null,
          siteName: '',
          orderState: 1,
          userPhone: '',
          workName: '',
          pageNum: 1,
          pageSize: 10,
        },
        orders: [],
        siteOptions: [],
        total: 0,
        loading: false,
        notifications: [],
        notificationCount: 0,
        showNotifications: false,
        assignSiteDialogVisible: false,
        selectedSiteId: null,
        currentOrder: null,
        siteMap: {}, // 添加站点映射对象
        detailsDialogVisible: false,
        currentOrderDetails: {
          orderNumber: '',
          userName: '',
          userPhone: '',
          startTime: '',
          orderState: null,
          totalAmount: '',
          creatTime: '',
          workName: '',
          siteName: '',
          userAddress: '',
          wasteList: []
        },
      };
    },
    methods: {
      // 获取订单数据
      fetchOrders() {
        const { dateRange, ...restQuery } = this.query;
        const params = {
          ...restQuery,
          startTime: dateRange && dateRange[0] ? dateRange[0] : null,
          endTime: dateRange && dateRange[1] ? dateRange[1] : null,
          pageNum: this.query.pageNum,
          pageSize: this.query.pageSize
        };

        // 移除空值参数
        Object.keys(params).forEach(key => {
          if (params[key] === null || params[key] === undefined || params[key] === '') {
            delete params[key];
          }
        });

        axios
          .get('/zsd-order/order-info/findAllOrder', { params })
          .then((response) => {
            if (response.data.code === 200) {
              const pageData = response.data.data;
              this.orders = pageData.records || []; // 设置订单数据
              this.total = pageData.total || 0; // 设置总条数
            } else {
              this.$message.error('查询失败：' + response.data.msg);
            }
          })
          .catch((error) => {
            console.error('请求出错：', error);
            this.$message.error('请求出错，请稍后再试');
          });
      },
  
      // 取消订单
      handleCancelOrder(row) {
        this.$prompt('请输入取消原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /.+/,
          inputErrorMessage: '取消原因不能为空',
        })
          .then(({ value }) => {
            const params = {
              orderNumber: row.orderNumber,
              remarks: value,
            };
  
            axios
              .put('/zsd-order/order-info/cancelOrder', params)
              .then((response) => {
                if (response.data.code === 200) {
                  this.$message.success('订单取消成功');
                  this.fetchOrders(); // 刷新订单列表
                } else {
                  this.$message.error('取消失败：' + response.data.msg);
                }
              })
              .catch((error) => {
                console.error('请求出错：', error);
                this.$message.error('请求出错，请稍后再试');
              });
          })
          .catch(() => {
            this.$message.info('已取消操作');
          });
      },
  
      // 分配站点
      handleAssignSite(row) {
        this.currentOrder = row;
        this.selectedSiteId = null;
        this.assignSiteDialogVisible = true;
      },

      // 确认分配站点
      confirmAssignSite() {
        if (!this.selectedSiteId) {
          this.$message.warning('请选择站点');
          return;
        }

        const params = {
          orderNum: this.currentOrder.orderNumber,
          siteId: this.selectedSiteId
        };

        axios.put('/zsd-order/order-info/adminUpdateOrder', params)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('站点分配成功');
              this.assignSiteDialogVisible = false;
              this.fetchOrders(); // 刷新订单列表
            } else {
              this.$message.error('分配失败：' + response.data.msg);
            }
          })
          .catch(error => {
            console.error('请求出错：', error);
            this.$message.error('请求出错，请稍后再试');
          });
      },

      // 获取站点名称
      getSiteName(siteId) {
        return this.siteMap[siteId] || siteId;
      },

      // 获取站点列表并创建映射
      async fetchSites() {
        this.loading = true;
        try {
          const response = await axios.get('/zsd-merchant/site/list', {
            params: {
              pageNum: 1,
              pageSize: 100
            }
          });
          if (response.data.code === 200) {
            const sites = response.data.data.records;
            // 创建站点映射
            this.siteMap = sites.reduce((map, site) => {
              map[site.id] = site.siteName;
              return map;
            }, {});
            // 更新站点选项
            this.siteOptions = sites.map(site => ({
              value: site.id,
              label: site.siteName
            }));
          } else {
            console.error('获取站点列表失败:', response.data.msg);
          }
        } catch (error) {
          console.error('请求站点列表出错:', error);
        } finally {
          this.loading = false;
        }
      },
  
      // 获取订单状态的中文描述
      getOrderState(state) {
        const stateMap = {
          1: '已创建',
          2: '已确认',
          3: '已接取',
          4: '待接取',
          5: '已入库',
          6: '已取消',
          7: '待分配',
        };
        return stateMap[state] || '未知状态';
      },
  
      // 切换每页条数
      handleSizeChange(size) {
        this.query.pageSize = size;
        this.query.pageNum = 1; // 重置页码
        this.fetchOrders();
      },
  
      // 切换页码
      handleCurrentChange(page) {
        this.query.pageNum = page;
        this.fetchOrders();
      },

    // 处理WebSocket消息
    handleWebSocketMessage(message) {
      // 如果是纯文本消息
      if (message.type === 'text') {
        this.notifications.unshift({
          id: Date.now(),
          type: 'info',
          title: '新消息',
          content: message.content,
          time: new Date().toLocaleTimeString(),
          read: false
        });
        this.notificationCount++;
        
        // 显示通知
        this.$notify({
          title: '新消息',
          message: message.content,
          type: 'info',
          duration: 5000,
          position: 'top-right'
        });
      } else {
        // 处理其他类型的消息
        this.notifications.unshift({
          id: Date.now(),
          type: message.type || 'info',
          title: message.title || '新消息',
          content: message.content,
          time: new Date().toLocaleTimeString(),
          read: false
        });
        this.notificationCount++;
        
        // 显示通知
        this.$notify({
          title: message.title || '新消息',
          message: message.content,
          type: message.type || 'info',
          duration: 5000,
          position: 'top-right'
        });
      }
    },

    // 标记通知为已读
    markNotificationAsRead(notification) {
      notification.read = true;
      this.notificationCount = this.notifications.filter(n => !n.read).length;
    },

    // 清除所有通知
    clearNotifications() {
      this.notifications = [];
      this.notificationCount = 0;
    },

    // 从token中获取用户ID的方法
    getUserIdFromToken(token) {
      try {
        const base64Url = token.split('.')[1];
        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
        const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
          return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        }).join(''));

        const payload = JSON.parse(jsonPayload);
        return payload.id || null;
      } catch (error) {
        console.error('解析token失败:', error);
        return null;
      }
    },

    // 获取废品类型列表
    fetchWasteTypes() {
      axios
        .get("/zsd-waste/waste-type/selWasteType")
        .then((response) => {
          if (response.data.code === 200) {
            this.wasteTypes = response.data.data || [];
          } else {
            this.$message.error("获取废品类型失败：" + response.data.msg);
          }
        })
        .catch((error) => {
          console.error("请求出错：", error);
          this.$message.error("请求出错，请稍后再试");
        });
    },

    getWasteTypeName(typeId) {
      if (!typeId) return '-';
      const type = this.wasteTypes.find(t => t.id === typeId);
      return type ? type.wasteTypeName : typeId;
    },

    // 查看订单详情
    async handleViewDetails(row) {
      // 重置当前订单详情
      this.currentOrderDetails = {
        orderNumber: '',
        userName: '',
        userPhone: '',
        startTime: '',
        orderState: null,
        totalAmount: '',
        creatTime: '',
        workName: '',
        siteName: '',
        userAddress: '',
        wasteList: []
      };
      
      // 显示对话框
      this.detailsDialogVisible = true;
      
      try {
        // 先设置基本信息
        Object.keys(row).forEach(key => {
          this.$set(this.currentOrderDetails, key, row[key]);
        });

        // 获取废品详情
        const wasteResponse = await axios.get('/zsd-order/order-waste/findOrderInfo', {
          params: { orderNumber: row.orderNumber }
        });
        
        if (wasteResponse.data.code === 200 && wasteResponse.data.data) {
          // 确保 wasteList 是数组
          const wasteList = Array.isArray(wasteResponse.data.data) ? wasteResponse.data.data : [wasteResponse.data.data];
          this.$set(this.currentOrderDetails, 'wasteList', wasteList);
          console.log('废品列表已更新:', this.currentOrderDetails.wasteList);
        }

        // 获取站点详情
        if (row.siteId) {
          const siteResponse = await axios.get('/zsd-merchant/site/find/id', {
            params: { id: row.siteId }
          });
          if (siteResponse.data.code === 200) {
            this.$set(this.currentOrderDetails, 'siteName', siteResponse.data.data.siteName);
          }
        }

        // 获取用户地址详情
        if (row.userAddress) {
          const addressResponse = await axios.get('/zsd-user/user-address/selUserAddressById', {
            params: { id: row.userAddress }
          });
          if (addressResponse.data.code === 200) {
            this.$set(this.currentOrderDetails, 'userAddress', addressResponse.data.data.address);
          }
        }
      } catch (error) {
        console.error('获取订单详情出错:', error);
        this.$message.error('获取订单详情失败');
      }
    },
    },
    mounted() {
      this.fetchOrders(); // 页面加载时自动查询
      this.fetchSites();
      this.fetchWasteTypes();

      // 获取token并连接WebSocket
      const loginUser = JSON.parse(localStorage.getItem('loginUser'));
      if (loginUser && loginUser.token) {
        // 先获取管理员信息
        axios.get('/zsd-permission/admin-info/selAdminInfo')
          .then(response => {
            if (response.data.code === null) {
              const adminInfo = response.data.data;
              // 确保之前的连接已关闭
              if (webSocketClient.ws) {
                webSocketClient.close();
              }
              // 使用管理员ID和token建立新连接
              webSocketClient.connect(loginUser.token, adminInfo.id);
              webSocketClient.addMessageHandler(this.handleWebSocketMessage);
            } else {
              console.error('获取管理员信息失败：', response.data.msg);
            }
          })
          .catch(error => {
            console.error('获取管理员信息出错：', error);
          });
      }
    },
    beforeDestroy() {
      // 组件销毁前移除消息处理器
      webSocketClient.removeMessageHandler(this.handleWebSocketMessage);
    }
  };
  </script>

<style scoped>
/* ... 原有样式 ... */

.notification-icon {
  position: fixed;
  top: 20px;
  right: 20px;
  cursor: pointer;
  z-index: 1000;
}

.notification-icon i {
  font-size: 24px;
  color: #606266;
}

.notification-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.notification-header {
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.notification-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.notification-item {
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
  transition: background-color 0.3s;
}

.notification-item:hover {
  background-color: #f5f7fa;
}

.notification-item.unread {
  background-color: #f0f9eb;
}

.notification-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.notification-message {
  color: #606266;
  margin-bottom: 5px;
}

.notification-time {
  font-size: 12px;
  color: #909399;
}
</style>